package com.topisv.tms.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;

import com.topisv.tms.entity.Area;
import com.topisv.tms.entity.AreaGroup;

public interface AreaDao extends PagingAndSortingRepository<Area, Long>, JpaSpecificationExecutor<Area> {
	List<Area> findByStatus(String status);
	
	List<Area> findByAreaTypeAndArea(String areaType,Area area);
	
	@Query("select area from Area area where area.areaType = 2 or area.areaType = 3")
	List<Area> findParents();
	
	@Query("select area from Area area where area.area.id=1")
	List<Area> findProvoce();
	
	List<Area> findByAreaType(String areaType);
	
	Area findByAreaCode(String areaCode);
	
	@Query("select area from Area area where area.areaName like ? and area.areaType=3 and area.area.id=?")
	Area findByAreaNameAndParentId(String areaName,Long parentId);
	
	Area findByAreaName(String areaName);
	@Query("select area from Area area where area.areaName like ? and area.areaType=2")
	Area findByAreaName2(String areaName);
	@Modifying
	@Query("select ar from Area ar where ar.areaGroup.id = ?1 and (areaType = 2 or areaType = 3)")
	List<Area> findByAreaGroupId(Long id);

	@Modifying
	@Query("select ar from Area ar where ar.area.id = ?1")
	List<Area> getSubAreasById(Long id);
	
	@Modifying
	@Query("select ar from Area ar where ar.areaGroup.id = ?1")
	List<Area> getByAreaGroupId(Long id);

	//根据上服务网点ID，查找它所覆盖的区域，然后修改这些区域的服务网点
	@Modifying
	@Query("update Area area set area.areaGroup=?1 where area.areaGroup.id=?2")
	void updateAreaGroup(AreaGroup areaGroup, long areaGroupId);

	//根据上父区域的ID，修改子区域所属的服务网点
	@Modifying
	@Query("update Area area set area.areaGroup=?1 where area.area.id=?2")
	void updateAreaGroupByParentId(AreaGroup areaGroup, long parentId);
	
	//根据上爷区域的ID，修改孙区域所属的服务网点
	@Modifying
	@Query("update Area area set area.areaGroup=?1 where area.area.area.id=?2")
	void updateAreaGroupByGrandParentId(AreaGroup areaGroup, long grandParentId);
}